﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MuseLibraryTests
{
    public static class Extensions
    {
        public static List<bool> ToBools(this String bits)
        {
            var output = new List<bool>();
            for (int i = 0; i < bits.Length; i++)
            {
                switch (bits[i])
                {
                    case '1':
                        output.Add(true);
                        break;
                    case '0':
                        output.Add(false);
                        break;
                    case ' ':
                        break;
                }
            }

            return output;
        }

        public static int ToTruncatedBinary(this int value, int alphabetSize, out int bits)
        {
            // Set k = floor(log2(n)), i.e., k such that 2^k <= n < 2^(k+1).
            int k = 0, t = alphabetSize;
            while (t > 1)
            {
                k++;
                t >>= 1;
            }

            // Set u to the number of unused codewords = 2^(k+1) - n.
            int u = (1 << k + 1) - alphabetSize;

            if (value < u)
                return Binary(value, k, out bits);
            return Binary(value + u, k + 1, out bits);
        }

        public static int Binary(this int value, int codewordLength, out int bits)
        {
            var output = 0;
            bits = 0;
            while (value != 0)
            {
                if ((value % 2) != 0)
                {
                    output += 1 << bits;
                }

                bits++;
                value >>= 1;
            }

            while (bits < codewordLength)
            {
                bits++;
            }

            return output;
        }
    }
}
